package com.zjw.zy.heart.wbsocket;


import com.zjw.zy.heart.utils.LogUtils;
import com.zjw.zy.heart.wbsocket.socket.WsMessage;
import jakarta.websocket.CloseReason;
import jakarta.websocket.Session;
import lombok.NonNull;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class WsDispatcher {


    private static final String TAG = "WsMessageDispatcher";
    private final List<IWSMessageHandler> messageHandlers = new ArrayList<>();
    private final List<IWSConnectHandler> connectHandlers = new ArrayList<>();

    public void addWsMessageInterceptor(@NonNull IWSMessageHandler handler) {
        if (messageHandlers.contains(handler)) {
            return;
        }
        messageHandlers.add(handler);
    }

    public void addWsConnectInterceptor(@NonNull IWSConnectHandler handler) {
        if (connectHandlers.contains(handler)) {
            return;
        }
        connectHandlers.add(handler);
    }

    public void removeWsMessageInterceptor(@NonNull IWSMessageHandler handler) {
        messageHandlers.remove(handler);
    }

    public void removeWsConnectInterceptor(@NonNull IWSConnectHandler handler) {
        connectHandlers.remove(handler);
    }

    public void dispatchWsMessage(@NonNull WsMessage message) {
        for (IWSMessageHandler handler : messageHandlers) {
            if (handler.onInterceptWsMessage(message)) {
                LogUtils.d(TAG, "dispatchWsMessage->" + handler + " " + message);
                handler.onHandleWsMessage(message);
            }
        }
    }

    public void dispatchWsOpen(Session session, String username) {
        for (IWSConnectHandler handler : connectHandlers) {
            if (handler.onInterceptOpen(session)) {
                LogUtils.d(TAG, "dispatchWsOpen->" + handler + " " + username);
                handler.onHandleOpen(session, username);
            }
        }
    }

    public void dispatchWsClose(Session session, CloseReason closeReason) {
        for (IWSConnectHandler handler : connectHandlers) {
            if (handler.onInterceptClose(session)) {
                LogUtils.d(TAG, "dispatchWsOpen->" + handler + " " + closeReason);
                handler.onHandleClose(session, closeReason);
            }
        }
    }

}
